package cn.seaboot.excel.sax;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.util.CellRangeAddress;
import org.dom4j.Attribute;
import org.dom4j.Element;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;

/**
 * parse tag: td、th
 *
 * @author Mr.css
 * @version 2025-07-01 14:37
 */
public class TableCellParser implements DocumentParser {

    /**
     * 要操作的 excel 上下文
     */
    private ExcelContext context;

    public ExcelContext getContext() {
        return context;
    }

    @Override
    public void parse(Element cell) throws IOException {
        Cell ec = context.nextCell();

        // 合并单元格的起始单元格
        Attribute colspan = cell.attribute("colspan");
        Attribute rowspan = cell.attribute("rowspan");
        if (colspan != null || rowspan != null) {
            // merge info
            CellRangeAddress address = createCellAddresses(ec, rowspan, colspan);
            this.context.mergeRegion(address);
        }

        // set value
        ec.setCellValue(cell.getText());
    }

    /**
     * 单元格合并信息
     *
     * @param cell    其实单元格
     * @param rowspan 合并列数
     * @param colspan 合并行数
     * @return 合并区域
     */
    @SuppressWarnings("ALL")
    public @NotNull CellRangeAddress createCellAddresses(Cell cell, Attribute rowspan, Attribute colspan) {
        int rn = cell.getRowIndex(), cn = cell.getColumnIndex();

        // table cell will be merged
        int endRow = rn;
        if (rowspan != null) {
            endRow = rn + Integer.parseInt(rowspan.getText()) - 1;
        }

        int endCol = cn;
        if (colspan != null) {
            endCol = cn + Integer.parseInt(colspan.getText()) - 1;
        }

        // create empty cell in range
        return new CellRangeAddress(rn, endRow, cn, endCol);
    }

    @Override
    public void setContext(ExcelContext context) {
        this.context = context;
    }
}
